import { useRef, useEffect } from 'react';

/**
 * 批量DOM更新工具
 */
export const useBatchDOMUpdates = () => {
  const updatesRef = useRef([]);
  const rafIdRef = useRef(null);

  const batchUpdate = (callback) => {
    updatesRef.current.push(callback);
    
    if (!rafIdRef.current) {
      rafIdRef.current = requestAnimationFrame(() => {
        const updates = updatesRef.current;
        updatesRef.current = [];
        rafIdRef.current = null;
        
        // 开始批量更新
        const fragment = document.createDocumentFragment();
        updates.forEach(cb => cb(fragment));
        document.body.appendChild(fragment);
      });
    }
  };

  useEffect(() => {
    return () => {
      if (rafIdRef.current) {
        cancelAnimationFrame(rafIdRef.current);
      }
    };
  }, []);

  return batchUpdate;
};

/**
 * 虚拟DOM列表渲染器
 */
export const VirtualListRenderer = ({ items, renderItem, containerHeight, rowHeight }) => {
  const containerRef = useRef(null);
  const [visibleRange, setVisibleRange] = useState({ start: 0, end: 0 });

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const calculateVisible = () => {
      const scrollTop = container.scrollTop;
      const visibleHeight = container.clientHeight;
      const startIdx = Math.floor(scrollTop / rowHeight);
      const endIdx = Math.ceil((scrollTop + visibleHeight) / rowHeight);

      setVisibleRange({
        start: Math.max(0, startIdx - 5),
        end: Math.min(items.length, endIdx + 5)
      });
    };

    calculateVisible();
    container.addEventListener('scroll', calculateVisible);
    return () => container.removeEventListener('scroll', calculateVisible);
  }, [items.length, rowHeight]);

  const transform = `translateY(${visibleRange.start * rowHeight}px)`;
  
  return (
    <div ref={containerRef} style={{ height: containerHeight, overflow: 'auto' }}>
      <div style={{ height: items.length * rowHeight, position: 'relative' }}>
        <div style={{ position: 'absolute', width: '100%', transform }}>
          {items.slice(visibleRange.start, visibleRange.end).map((item, idx) => (
            <div key={idx + visibleRange.start} style={{ height: rowHeight }}>
              {renderItem(item, idx + visibleRange.start)}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

/**
 * 减少布局抖动的测量Hook
 */
export const useStableMeasure = () => {
  const animationFrameRef = useRef(null);
  const [measures, setMeasures] = useState({
    width: 0,
    height: 0
  });

  const measureRef = useCallback(node => {
    if (!node) return;

    const updateMeasures = () => {
      if (node) {
        const rect = node.getBoundingClientRect();
        setMeasures({
          width: rect.width,
          height: rect.height
        });
      }
      animationFrameRef.current = null;
    };

    if (!animationFrameRef.current) {
      animationFrameRef.current = requestAnimationFrame(updateMeasures);
    }

    // 初始测量
    if (measures.width === 0 && measures.height === 0) {
      updateMeasures();
    }

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, []);

  return [measures, measureRef];
};
